#include <QSsl>
#include <QUrl>
#include <QSslSocket>
#include <QSslConfiguration>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QVariant>
#include <QDebug>
#include <QRegularExpression>
#include "HttpClient.h"


HttpClient::HttpClient() : mAccessManager(NULL)
{
    mAccessManager = new QNetworkAccessManager(this);
}

HttpClient::~HttpClient()
{
    if (mAccessManager) {
        delete mAccessManager;
        mAccessManager = NULL;
    }
}

void HttpClient::doRequest(HttpClient::HttpMethod method, QString &url,QString postData)
{
    qDebug("do request...");
    QNetworkRequest request;
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");
    //request.setRawHeader("cookie", "_ga=GA1.2.6986038.1687843880; _gid=GA1.2.1853731263.1687843880;");

    QSslConfiguration cfg = request.sslConfiguration();
    cfg.setPeerVerifyMode(QSslSocket::VerifyNone);
    cfg.setProtocol(QSsl::AnyProtocol);

    request.setSslConfiguration(cfg);
    request.setUrl(QUrl(url));

    if (method == POST) {
        request.setRawHeader("Content-Type", "application/json;charset=utf-8");
        //request.setRawHeader("Content-Type","application/x-www-form-urlencoded");
        request.setRawHeader("Accept", "application/json");

        QByteArray data=postData.toUtf8();
        //data.append("name=admin&password=123456");
        mReply = mAccessManager->post(request, data);
    } else if (method == GET) {
        //request.setRawHeader("Content-Type", "text/html; charset=UTF-8");
        request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        mReply = mAccessManager->get(request);
    }
    connect(mReply, SIGNAL(finished()), this, SLOT(postFinishSlot()));
    connect(mReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(httpErrorSlot(QNetworkReply::NetworkError)));
}

void HttpClient::doRequestGet(QString &url)
{
    doRequest(HttpClient::GET,url);
}

void HttpClient::doRequestPost(QString &url,QString postData)
{
    doRequest(HttpClient::POST,url,postData);
}

void HttpClient::postFinishSlot()
{
    QVariant statusCode = mReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    int code = statusCode.toInt();
    QByteArray resp = mReply->readAll();
    QList<QByteArray> hdrNames = mReply->rawHeaderList();

    qDebug("response headers:");
    for (int i = 0; i < hdrNames.size(); i ++) {
        QByteArray hdrName = hdrNames.at(i);
        QByteArray hdrCtx = mReply->rawHeader(hdrName);
        qDebug("%s: %s", hdrName.constData(), hdrCtx.constData());
    }
    qDebug()<<QString(resp);
    emit postFinish(mReply->url().toString(),code, resp);
}

void HttpClient::httpErrorSlot(QNetworkReply::NetworkError err)
{
    emit httpError(err);
}

QString HttpClient::Html2Text(QString htmlString)
{
    // Regular expression to match HTML tags
    QRegularExpression htmlTags("<[^>]*>");

    // Remove HTML tags from string
    QString plainText = htmlString.remove(htmlTags);

    // Output result
    return plainText;
}
